/*
 * @Description: vue3 api自动引入，vite专用
 * @Author: xjc
 * @Date: 2022-06-23 09:15:28
 * @LastEditTime: 2022-06-23 09:19:49
 * @LastEditors: xjc
 */
const vue3Api = ['ref', 'computed', 'reactive', 'onMounted', 'watchEffect', 'watch']

export default function autoImportPlugin() {
  return {
    name: 'vue3api-auto-import-plugin', // 必须的，将会在 warning 和 error 中显示
    enforce:'pre',
    transform(code,id){
      const vueReg = /\.vue$/
      if (vueReg.test(id)) {
        const helpers = new Set()
        vue3Api.forEach(api => {
          const reg = new RegExp(api + '(.*)')
          if (reg.test(code)) {
            helpers.add(api)
          }
        })
        return code.replace('<script setup>',`<script setup>
          import {${[...helpers].join(',')}} from 'vue'
        `)
      }
      
      return code
    }
  }
}